package cn.framelife.rainbow.db.creator.part;

import java.util.Set;

import cn.framelife.rainbow.db.entity.ClazzProperty;
import cn.framelife.rainbow.db.entity.ImportSet;
import cn.framelife.rainbow.db.entity.Property;
import cn.framelife.rainbow.util.FreemarkerUtil;
import cn.framelife.rainbow.util.StringUtil;

public class ServiceCreator {
	private String projectName;
	private String packageURL;
	
	public ServiceCreator(String projectName, String packageURL) {
		this.projectName = projectName;
		this.packageURL = packageURL;
	}
	
	public void createCodeForService(ClazzProperty entity) throws Exception{
		ClazzProperty iService = createIService(entity);
		FreemarkerUtil.createIService(iService);
		ClazzProperty service = createService(iService, entity);
		FreemarkerUtil.createService(service);
	}

	/**
	 * 生成实体类相关的Service接口对象
	 *
	 * @param reverseProperty
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	public ClazzProperty createIService(ClazzProperty entity) throws Exception {
		Set<String> imports = new ImportSet<String>();
		ClazzProperty iService = new ClazzProperty();
		iService.setClassName(StringUtil.merge("I",entity.getClassName(),"Service"));
		iService.setProjectName(projectName);
		
		iService.setPackageURL(StringUtil.merge(packageURL,".service"));
		
		imports.add(entity.getPkType().getJavaTypePackage());
		imports.add(StringUtil.merge(entity.getPackageURL(),".",entity.getClassName()));
		iService.setImports(imports);
		
		iService.setEntityName(entity.getClassName());
		iService.setPkType(entity.getPkType());
	
		return iService;
	}
	
	/**
	 * 生成实体类相关的Service对象
	 *
	 * @param reverseProperty
	 * @param iService
	 * @param iDao
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	public ClazzProperty createService(ClazzProperty iService,ClazzProperty entity) throws Exception {
		Set<String> imports = new ImportSet<String>();
		ClazzProperty serivce = new ClazzProperty();
		serivce.setClassName(StringUtil.merge(entity.getClassName(),"Service"));
		serivce.setProjectName(projectName);
		
		serivce.setPackageURL(StringUtil.merge(packageURL,".service.impl"));
		
		imports.add(entity.getPkType().getJavaTypePackage());
		imports.add(StringUtil.merge(entity.getPackageURL(),".",entity.getClassName()));
		imports.add(StringUtil.merge(iService.getPackageURL(),".",iService.getClassName()));
		imports.add(StringUtil.merge(packageURL,".dao.I",entity.getClassName(),"Dao"));
		serivce.setImports(imports);
		
		serivce.setEntityName(entity.getClassName());
		serivce.setPkType(entity.getPkType());
		serivce.setInterfaceName(iService.getClassName());
		
		Property property = new Property();
		property.setType(StringUtil.merge("I",entity.getClassName(),"Dao"));
		property.setName(StringUtil.merge(StringUtil.toLowerCaseFirstOne(entity.getClassName()),"Dao"));
		serivce.setProperty(property);

		return serivce;
	}
}
